﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Xml.Linq;
using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Xna.Framework.Input.Touch;
using System.Windows.Media.Imaging;

namespace GameForKids
{
    public class DrawGameplay : DrawableGameComponent
    {
     
        // bien dem thoi gian
        public float milisecon = 0;
        // hien thi thoi gian choi
        public string timePlay = "";

        private SpriteFont font;

        // trang thai cua game
        private enum GameStateMini
        {
            playing,
            checking,
            win,
        }

        public bool iswin = false;
        SpriteFont helpfont;
        //luu diem 1 lan, tranh lap lai
        private GameStateMini gamestatemini;
        public int moved = 0;
        // tao co so du lieu
        private string strConnectionString = @"isostore:/DrawNumbersDB.sdf";

        // cong thuc tinh diem

        public static string CongThucGoc = "(12*L*10)/N+3";
        public static string CongThucHienTai = "";

        private Texture2D apple;
        private Vector2[] appleLocation;
        private Texture2D numberImage;
        private Vector2 numberLocation;
        private Texture2D circle;
        private List<Vector2> circlePosition;
        private int number;
        private Button OKButton;
        private Button CancelButton;

        public string NameImage = "";
        public int sizeLimit = 0;

        private List<Vector2> listTruePoint;
        private List<Vector2> _listTruePoint;
        private List<Vector2> listFalsePoint;
        private List<Vector2> _listFalsePoint;
        private int numOFtrue = 0;
        private int numOfFalse = 0;

        public DrawGameplay(Game game): base(game)
        {
 
            NameImage = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            sizeLimit = NameImage.Length-1;
            helpfont = this.Game.Content.Load<SpriteFont>("Fonts/HelpFont");
            font = this.Game.Content.Load<SpriteFont>("Fonts/ChartFont");
            apple = this.Game.Content.Load<Texture2D>("DrawLetterGame/Images/apple");
            numberLocation = new Vector2(525, 30);
            circle = this.Game.Content.Load<Texture2D>("DrawLetterGame/Images/circle");
            circlePosition = new List<Vector2>();
            listFalsePoint = new List<Microsoft.Xna.Framework.Vector2>();
            listTruePoint = new List<Microsoft.Xna.Framework.Vector2>();
            _listFalsePoint = new List<Microsoft.Xna.Framework.Vector2>();
            _listTruePoint = new List<Microsoft.Xna.Framework.Vector2>();

            OKButton = new Button(this.Game.Content.Load<Texture2D>("DrawLetterGame/Images/ok_button"),
                this.Game.Content.Load<Texture2D>("DrawLetterGame/Images/ok_button_press"),
                this.Game.Content.Load<Texture2D>("DrawLetterGame/Images/ok_button_press"));
            OKButton.Location = new Point((int)numberLocation.X-20-OKButton.width, (int)numberLocation.Y+350);
            OKButton.Clicked += OKButton_Clicked;


            CancelButton = new Button(this.Game.Content.Load<Texture2D>("DrawLetterGame/Images/cancel_button"),
                this.Game.Content.Load<Texture2D>("DrawLetterGame/Images/cancel_button_press"),
                this.Game.Content.Load<Texture2D>("DrawLetterGame/Images/cancel_button_press"));
            CancelButton.Location = new Point((int)numberLocation.X + 20, (int)numberLocation.Y + 350);
            CancelButton.Clicked += CancelButton_Clicked;

            appleLocation = new Vector2[9];
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    appleLocation[i*3 + j] = new Vector2(120+(20+apple.Width)*(j%3),100+(20+apple.Height)*i);
                }

            }

            gamestatemini = GameStateMini.playing;

            // tao csdl
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                if (readAndWriteDB.DatabaseExists() == false)
                {
                    readAndWriteDB.CreateDatabase();
                }
            }


            // lay cong thuc
            using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isolatedStorageFile.FileExists("CongThuc" + GameForKids.gameState.ToString() + ".txt"))
                {
                    using (IsolatedStorageFileStream isfs = isolatedStorageFile.OpenFile("CongThuc" + GameForKids.gameState.ToString() + ".txt", FileMode.Open))
                    {
                        using (StreamReader reader = new StreamReader(isfs))
                        {
                            while (!reader.EndOfStream)
                            {
                                CongThucHienTai = reader.ReadLine();
                            }
                        }
                    }
                }
            }
            if (CongThucHienTai == "" || CongThucHienTai == null)
                CongThucHienTai = CongThucGoc;

        }

        void CancelButton_Clicked(object sender, EventArgs e)
        {
            _listFalsePoint.Clear();
            _listTruePoint.Clear();
            foreach (Vector2 v in listFalsePoint)
                _listFalsePoint.Add(v);
            foreach (Vector2 v2 in listTruePoint)
                _listTruePoint.Add(v2);
            numOFtrue = 0;
            numOfFalse = _listTruePoint.Count;
            circlePosition.Clear();
        }

        public void RestartLevel()
        {
            iswin = false;
            _listFalsePoint.Clear();
            _listTruePoint.Clear();
            foreach (Vector2 v in listFalsePoint)
                _listFalsePoint.Add(v);
            foreach (Vector2 v2 in listTruePoint)
                _listTruePoint.Add(v2);
            numOFtrue = 0;
            numOfFalse = _listTruePoint.Count;
            circlePosition.Clear();
            moved = 0;
            milisecon = 0;
        }

        void OKButton_Clicked(object sender, EventArgs e)
        {
            iswin = true;
        }


        // giai phong bo nho
        public void unload()
        {

        }

      
        // luu theo dang ID - ten  - level - diem - ngay
        public void saveScore(int diem)
        {
            string _name = GameForKids.userName;
            int _level = -1;
            int _score = diem;
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                DataScore newscore = new DataScore
                {
                    ID = DateTime.Now.ToString(),
                    name = _name,
                    level = _level,
                    score = _score,
                    day = DateTime.Today.ToShortDateString()
                };
                readAndWriteDB.TableScore.InsertOnSubmit(newscore);
                readAndWriteDB.SubmitChanges();
            }
        }
        private IList<DataScore> getListDataScore(string _name, int _level)
        {
            IList<DataScore> listDataScore = null;
            using (ReadAndWrite readAndWrite = new ReadAndWrite(strConnectionString))
            {
                IQueryable<DataScore> dataScoreQuery = from data in readAndWrite.TableScore where data.name.Equals(_name) && data.level == _level select data;
                listDataScore = dataScoreQuery.ToList();
            }
            return listDataScore;
        }

        public void startNewLevel(int _level)
        {
            iswin = false;
            ChartScreen.listDataScore = this.getListDataScore(GameForKids.userName, -1);
            ChartScreen.levelOfGame = -1;
            number = _level;
            numberImage = this.Game.Content.Load<Texture2D>("DrawLetterGame/Images/" + NameImage[_level]);
            circlePosition.Clear();
            listTruePoint.Clear();
            listFalsePoint.Clear();
            _listTruePoint.Clear();
            _listFalsePoint.Clear();
            WriteableBitmap writeableBmp = BitmapFactory.New(numberImage.Width, numberImage.Height);
            writeableBmp.GetBitmapContext();
            writeableBmp = BitmapFactory.New(1, 1).FromResource("Images/"+ NameImage[_level]+"_copy.png");
            for (int i = 0; i < numberImage.Width; i++)
                for (int j = 0; j < numberImage.Height; j++)
                {
                    System.Windows.Media.Color color = writeableBmp.GetPixel(i, j);
                    if (color.ToString() == "#FF000000")
                        listTruePoint.Add(new Vector2(i+numberLocation.X-numberImage.Width/2,j+numberLocation.Y));
                    if (color.ToString() == "#FFFF0000")
                        listFalsePoint.Add(new Vector2(i + numberLocation.X - numberImage.Width / 2, j + numberLocation.Y));
                }
            foreach(Vector2 v in listFalsePoint)
            _listFalsePoint.Add(v);
            foreach(Vector2 v2 in listTruePoint)
            _listTruePoint.Add(v2);
            numOFtrue = 0;
            numOfFalse = _listTruePoint.Count;
            moved = 0;
            milisecon = 0;
        }
        //tinh diem
        public int getScore()
        {
            int diem = 0;
            diem = (numOFtrue*10) / (numOFtrue + numOfFalse);
            if (diem < 0) diem = 0;
            if (diem > 10) diem = 10;
            return diem;
            

        }





        public override void Initialize()
        {
            base.Initialize();
        }


        public override void Update(GameTime gameTime)
        {
        
            float elapsed = (float)gameTime.ElapsedGameTime.Milliseconds;
            // bat dau choi thi tinh gio
            if (DrawGame.viewState == DrawGame.ViewState.Playing)
            {
                milisecon += elapsed;
                setTimePlay();
            }
           
          
            base.Update(gameTime);
        }

        public void setTimePlay()
        {
            timePlay = ((int)milisecon / 60000).ToString() + " : " + (((int)milisecon / 1000) % 60).ToString();
        }

        public virtual void Draw(GameTime gametime, SpriteBatch spriteBatch)
        {
            if (circlePosition != null)
            {
                foreach (Vector2 position in circlePosition)
                {
                    spriteBatch.Draw(circle, new Vector2(position.X-circle.Width/2,position.Y-circle.Height/2), Color.White);
                }
            }
            if(number < 10)
            for (int i = 0; i < number; i++)
            {
                spriteBatch.Draw(apple, appleLocation[i], Color.White);
            }
            spriteBatch.Draw(numberImage, new Vector2(numberLocation.X-numberImage.Width/2,numberLocation.Y), Color.White);

            OKButton.Draw(spriteBatch);
            CancelButton.Draw(spriteBatch);

            spriteBatch.DrawString(helpfont, timePlay, new Vector2(10, 250), Color.White);
            spriteBatch.DrawString(helpfont, moved.ToString(), new Vector2(740, 250), Color.White);

        }

        public void TouchEvent(InputState input)
        {
         
            if (gamestatemini == GameStateMini.playing)
            {
                TouchCollection touches = input.TouchState;
                if (touches.Count > 0)
                {
                    TouchLocation touch = touches[0];
                    {
                        OKButton.TouchEvent(touch);
                        CancelButton.TouchEvent(touch);
                    }
                }
                foreach (GestureSample gesture in input.Gestures)
                {
                    if (gesture.GestureType == GestureType.FreeDrag)
                    {
                        if ((gesture.Position.X >= numberLocation.X - 10 - numberImage.Width/2 && gesture.Position.X <= numberLocation.X + numberImage.Width/2 + 10)
                            && (gesture.Position.Y >= numberLocation.Y - 10 && gesture.Position.Y <= numberLocation.Y + numberImage.Height + 10))
                        {
                            Vector2 tmp = new Vector2(gesture.Position.X , gesture.Position.Y);
                            circlePosition.Add(tmp);
                            if (_listTruePoint.Count > 0)
                            {
                                for (int i = 0; i < _listTruePoint.Count; i++)
                                {
                                    int d = (int)Vector2.Distance(tmp, _listTruePoint[i]);
                                    if (d <= 8)
                                    {
                                        _listTruePoint.RemoveAt(i);
                                        i--;
                                        numOfFalse--;
                                        numOFtrue++;
                                    }
                                }
                            }
                            if (_listFalsePoint.Count > 0)
                            {
                                for (int i = 0; i < _listFalsePoint.Count; i++)
                                {
                                    int d = (int)Vector2.Distance(tmp, _listFalsePoint[i]);
                                    if (d <= 5)
                                    {
                                        _listFalsePoint.RemoveAt(i);
                                        i--;
                                        numOfFalse++;
                                        numOFtrue--;
                                    }
                                }
                            }
                        }
                    }
                }
            }

          

        }
    }
}
